<template>
  <div id="encryptedDog">
    <div class="pageHead">
      <el-button type="primary" round size="medium" v-if="jurisdictionControl.J_AddDog" @click="isInsertDongle">获取当前加密狗</el-button>
    </div>
    <div class="pageMain">
      <ul>
        <li v-for="item in listData" :key="item.ID" class="listItem">
          <el-row class="listHead">
            <el-col :span="12">
              <span>加密狗别名: {{ item.alias }}</span>
            </el-col>
            <el-col :span="12">
              <div class="pull-right">
                <el-switch inactive-text="状态：" :disabled="jurisdictionControl.J_ChangeDog" v-model="item.usbStatus" @change="startAndStop(item)"></el-switch>
              </div>
            </el-col>
          </el-row>
          <el-row class="listMain">
            <el-col :span="8"><span class="glayFont">序列号：</span> {{ item.serialNumber }}</el-col>
            <el-col :span="8">
              <p class="pull-center"><span class="glayFont">绑定网址：</span> {{ item.url }}</p>
            </el-col>
            <el-col :span="8"><span class="pull-right" style="margin-right:50px;"><span class="glayFont">绑定时间：</span> {{ item.createTime }}</span></el-col>
          </el-row>
        </li>
        <li v-show="listData.length==0" class="notavailable">
          <img src="../../assets//images/available.png" alt="" srcset="">
        </li>
      </ul>
    </div>
    <!-- 启停弹框 -->
    <el-dialog :title="startAndStopPopUp.title" :visible.sync="startAndStopPopUp.isShow" width="20%" @closed="handleClose">
      <el-form :model="startAndStopParams" :rules="rules" ref="startAndStopForm" label-width="60px" style="padding: 40px 0;">
        <el-form-item label="密码" prop="AdminPwd">
          <el-input v-model="startAndStopParams.AdminPwd" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="cancel" round>取 消</el-button>
        <el-button size="medium" type="primary" @click="confirm" round :loading="isConfirmLoading">确 认</el-button>
      </span>
    </el-dialog>
    <!-- 添加加密狗弹框弹框 -->
    <el-dialog :title="serialPopup.title" :visible.sync="serialPopup.isShow" width="20%" @closed="handleClose2">
      <el-form :model="serialParams" :rules="rules" ref="serialForm" label-width="100px" style="padding: 40px 0;">
        <el-form-item label="序列号" prop="SerialNumber">
          <el-input v-model="serialParams.SerialNumber" placeholder="请输入序列号"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="serialPopup.isShow = false" round>取 消</el-button>
        <el-button size="medium" type="primary" @click="addEncryptedDog" round :loading="isConfirmLoading2">确 认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mixinsMethod } from '@/util/util';
import { mapState } from 'vuex';
import md5 from 'js-md5';
import * as dogMethed from '@/assets/js/NTAdminJavascript';
export default {
  name: 'encryptedDog',
  data() {
    return {
      jurisdictionControl: {
        J_AddDog: false, // 新增加密狗
        J_ChangeDog: true // 修改加密狗状态
      },
      listQuery: {
        pageIndex: 1,
        pageSize: 100
      },
      encryptedDogParams: { // 加密狗相关参数
        Alias: '', // 加密狗别名
        state: '' // 当前加密狗状态
      },
      listData: [],
      startAndStopParams: {
        CompanyId: '', // 公司ID
        UsbKey: '', // 加密狗唯一辨识（uid）
        Status: '', // 状态 1启用；2停用
        AdminPwd: '' // 管理员密码(MD5加密)
      },
      serialParams: {
        UsbKey: '', // 加密狗唯一辨识
        SerialNumber: '', // 加密狗序列号
        Alias: '', // 加密狗别名
      },
      serialPopup: {
        title: '',
        isShow: false
      },
      startAndStopPopUp: {
        title: '',
        isShow: false
      },
      isConfirmLoading: false,
      isConfirmLoading2: false,
      rules: {
        AdminPwd: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        SerialNumber: [
          { required: true, message: '请输入序列号', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    ...mapState({
      tagCurrent: state => state.tag.tagCurrent,
      userInfo: state => state.common.userInfo,
      moduleId: state => state.common.moduleId
    })
  },
  methods: {
    handleClose() {
      this.getTableData();
      // 清空绑定的数据
      this.clearObjVal(this.startAndStopParams);
    },
    handleClose2() {
      // 清空绑定的数据
      this.clearObjVal(this.serialParams);
    },
    cancel() {
      this.startAndStopPopUp.isShow = false;
      this.getTableData();
    },
    confirm() {
      this.$refs['startAndStopForm'].validate((valid) => {
        if (valid) {
          this.getConfiim();
        }
      });
    },

    getConfiim() { // 启停确认
      this.isConfirmLoading = true;
      let params = {
        id: this.startAndStopParams.id,
        usbStatus: this.startAndStopParams.usbStatus
      };
      this.$api.systemManagement.dogEdit(params, 2, md5(this.startAndStopParams.AdminPwd)).then(() => {
        this.startAndStopPopUp.isShow = false;
        this.$message({ message: '修改成功', type: 'success' });
        this.getTableData();
        setTimeout(() => {
          this.isConfirmLoading = false;
        }, 1000);
      });
    },

    addEncryptedDog() {
      this.$refs['serialForm'].validate((valid) => {
        if (valid) {
          this.isConfirmLoading2 = true;
          this.$api.systemManagement.dogEdit(this.serialParams, 1).then(() => {
            this.serialPopup.isShow = false;
            this.getTableData();
            setTimeout(() => {
              this.isConfirmLoading2 = false;
            }, 1000);
          });
        }
      });
    },
    startAndStop(item) { // 加密狗的启停操作
      // 2021-7-6 pt 如果是超级管理员就不用输入密码了
      // 如果不是则需要输入密码

      this.startAndStopParams.id = item.id;
      this.startAndStopParams.usbStatus = item.usbStatus ? 1 : 0;
      if (this.userInfo.isadmin) { // 超级管理员
        this.getConfiim();
        return;
      }
      this.$nextTick(() => { // 清空表单验证
        if (this.$refs['startAndStopForm']) {
          this.$refs['startAndStopForm'].resetFields();
        }
      });
      this.startAndStopPopUp = {
        title: '提示',
        isShow: true
      };
    },
    getTableData() {
      this.$api.systemManagement.GetDogPageList(this.listQuery).then(res => {
        if (!res.data.data) {
          this.listData = [];
          return;
        }
        let resData = res.data.data.items;
        resData.map(item => {
          item.usbStatus = item.usbStatus ? true : false;
        });
        this.listData = resData;
      });
    },
    isInsertDongle() {
      // 创建并初始化
      dogMethed.createAdminElementNT199();
      // DetectActiveX() 判断Clinet是否安装
      var create = dogMethed.DetectNT199AdminPlugin();
      if (create === false) {
        // 这里弹框确定下载插件
        this.$confirm('插件未安装,请下载并安装NT199_Security_Admin!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // window.open('http://yundaizhang.com/FileImport/NT199/NT199_Security_Admin.exe')
          window.location.href = 'http://yundaizhang.com/FileImport/NT199/NT199_Security_Admin.exe';
        }).catch(() => { // 取消
          // this.$store.commit('DEL_TAG', this.tagCurrent)
          // this.$router.back(-1)
        });
        return false;
      }

      // 测试浏览器兼容
      const browser = dogMethed.DetectBrowser();
      if (browser === 'Unknown') {
        alert('不支持该浏览器， 如果您在使用傲游或类似浏览器，请切换到IE模式');
        return false;
      }

      // 查找加密锁 判断是否插入
      let Rtn = dogMethed.NT199_AdminFindAll();
      if (Rtn <= 0) {
        alert('请先插入加密狗，错误码：' + dogMethed.NT199_AdminGetLastError());
        return false;
      }
      Rtn = dogMethed.NT199_NTCheckAdminPin('admin');
      if (Rtn !== 0) {
        alert('获取本地加密狗失败!');
        return false;
      }
      // 获取加密狗序列号
      const uid = dogMethed.NT199_AdminGetUID();
      if (uid == null || uid === '') {
        alert('获取加密狗序列号失败!');
        return false;
      }
      // 请求是否已经绑定过，如果已经绑定过则不往下执行
      this.$api.systemManagement.dogIsBind({ UsbKey: uid }).then(res => {
        let usbState = res.data.status; // 1为已绑定  2为未绑定
        if (usbState === 400) {
          this.$message({
            message: '当前加密狗已绑定',
            type: 'warning'
          });
          return false;
        } else if (usbState === 200) {
          // 获取当前加密狗操作
          // 加密狗操作：将网址写入U盘 下次打开电脑插入U盘自动打开该网址
          let url = 'http://www.yundaizhang.com/';
          let keyName = 'NT199'; // 加密狗别名
          let useIE = 0; // 默认
          Rtn = dogMethed.NT199_NTSetKeyInfo(keyName, url, useIE);
          if (Rtn !== 0) {
            alert('网址写入失败！' + dogMethed.NT199_AdminGetLastError());
            return false;
          }
          this.serialParams.UsbKey = uid;
          this.serialParams.Alias = keyName;
          this.serialParams.CompanyId = this.userInfo.CompanyId;
          this.$nextTick(() => { // 清空表单验证
            if (this.$refs['serialForm']) {
              this.$refs['serialForm'].resetFields();
            }
          });
          this.serialPopup = { // 打开弹框
            title: '获取当前加密狗',
            isShow: true
          };
        }
      });
    },
    getJurisdiction() {
      if (this.userInfo.isadmin) {
        this.jurisdictionControl = {
          J_AddDog: true, // 新增加密狗
          J_ChangeDog: false // 修改加密狗状态
        };
        return;
      }
      let params = {
        id: this.moduleId
      };
      this.$api.publicApi.GetActionInfo(params).then(res => {
        let resData = res.data.data;
        resData.map(item => {
          if (item.name === '添加加密狗') {
            this.jurisdictionControl.J_AddDog = true;
          }
          if (item.name === '修改状态') {
            this.jurisdictionControl.J_ChangeDog = false;
          }
        });
      });
    }
  },
  created() {
    this.getJurisdiction();
    this.getTableData();
  },
  mixins: [mixinsMethod]
};
</script>

<style lang="less">
#encryptedDog {
  padding: 30px 40px;
  .pageHead {
    padding: 11px 25px !important;
  }
  .pageMain {
    position: relative;
    padding: 20px 25px 0 25px;
    .el-switch__label,
    .glayFont {
      color: #8b9bb9;
    }
    .listItem {
      font-size: 14px;
      box-shadow: 0px 0px 20px #d4dcf0;
      .listHead {
        background: #f7f8fd;
        padding: 15px 50px;
      }
      .listMain {
        padding: 25px 50px;
      }
    }
    .notavailable {
      position: absolute;
      top: 0;
      right: 0;
      left: 0;
      bottom: 0;
      margin: 0 auto;
      display: flex;
      justify-content: center;
      align-items: center;
      img {
        width: 280px;
      }
    }
  }
}
</style>
